export function urlToBase64(url) {
    return new Promise((resolve, reject) => {
        console.log(url, "jinglail");
        let newUrl = url
        console.log(newUrl.match(/https:\/\//g));

        if (newUrl.match(/https:\/\//g).length > 1) {
            newUrl = newUrl.replace("@webp", "")
            const parts = newUrl.split('https://');
            // 取第二个匹配后的部分，并加上 https:// 前缀
            url = 'https://' + parts[2]; // 注意索引是 [2]，因为第一个是空字符串或无效部分
        }

        let image = new Image();
        console.log(image, "imagessdafasfsaffsad");

        image.onload = function () {
            console.log(url, "jinglail2");
            let canvas = document.createElement('canvas');
            canvas.width = this.naturalWidth;
            canvas.height = this.naturalHeight;
            // 将图片插入画布并开始绘制
            canvas.getContext('2d').drawImage(image, 0, 0);
            // result
            let result = canvas.toDataURL('image/png')
            // baseToBinary(result)
            base64toBlob(result)
            // resolve(result);
        };
        console.log(url, "jinglail3");
        image.setAttribute("crossOrigin", 'Anonymous');
        image.src = url;
        console.log(url, "jinglail4");
        // 图片加载失败的错误处理
        image.onerror = (e) => {
            console.log(e, 12313);

            reject(new Error('转换失败', e));
        };
    });
}

export function baseToBinary(base64) {
    const filename = 'image' + getDate(new Date())
    var arr = base64.split(',')  //去掉base64格式图片的头部
    var bstr = atob(arr[1])   //atob()方法将数据解码
    var leng = bstr.length
    var u8arr = new Uint8Array(leng)
    while (leng--) {
        u8arr[leng] = bstr.charCodeAt(leng) //返回指定位置的字符的 Unicode 编码
    }
    return new File([u8arr], filename, { type: contentType })
}

export async function urlToBinary(imageUrl) {
    try {
        // 1. 获取图片数据
        const response = await fetch(imageUrl);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        // 2. 获取ArrayBuffer
        const arrayBuffer = await response.arrayBuffer();

        // 3. 转换为Uint8Array
        return new Uint8Array(arrayBuffer);

    } catch (error) {
        console.error('图片转换失败:', error);
        throw error; // 重新抛出错误供调用方处理
    }
}


export function urlToFile(url, imageName) {
    return new Promise((resolve, reject) => {
        var blob = null
        var xhr = new XMLHttpRequest()
        xhr.open('GET', url)
        xhr.setRequestHeader('Accept', 'image/png')
        xhr.responseType = 'blob'
        xhr.onload = () => {
            blob = xhr.response
            let imgFile = new File([blob], imageName, { type: 'image/png' })
            resolve(imgFile)
        }
        xhr.onerror = (e) => {
            reject(e)
        }
        xhr.send()
    })
}

function base64toBlob(dataurl) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}


export async function urlToBase64Decrypt(url) {
    try {
        // 1. 获取图片资源
        const response = await fetch(url);
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

        // 2. 转换为 ArrayBuffer
        const arrayBuffer = await response.arrayBuffer();

        // 3. 转换为 Base64 字符串
        const base64String = btoa(
            new Uint8Array(arrayBuffer).reduce((data, byte) => data + String.fromCharCode(byte), '')
        );

        // 4. 添加 MIME 类型前缀（根据实际文件类型修改）
        const mimeType = url.endsWith('.png') ? 'image/png' :
            url.endsWith('.jpg') || url.endsWith('.jpeg') ? 'image/jpeg' :
                url.endsWith('.webp') ? 'image/webp' : 'application/octet-stream';

        return `data:${mimeType};base64,${base64String}`;
    } catch (error) {
        console.error('转换失败:', error);
        return null;
    }
}

export function formatDate(dateStr) {
    // 将原始字符串解析为Date对象
    console.log(dateStr, 'dateStr');

    if (dateStr.includes('hours ago')) {
        let time = dateStr.split(' ')[0]
        console.log('9999999');
        const timestamp = Date.now() - Number(time) * 60 * 60 * 1000;
        const pastTime = new Date(timestamp);

        // 使用解构赋值提取时间组件
        const [year, month, day, hours, minutes, seconds] = [
            pastTime.getFullYear(),
            String(pastTime.getMonth() + 1).padStart(2, '0'),
            String(pastTime.getDate()).padStart(2, '0'),
            String(pastTime.getHours()).padStart(2, '0'),
            String(pastTime.getMinutes()).padStart(2, '0'),
            String(pastTime.getSeconds()).padStart(2, '0')
        ];

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    } else {
        let dateObj = new Date(dateStr);

        let year = dateObj.getFullYear();
        let month = String(dateObj.getMonth() + 1).padStart(2, '0'); // JavaScript的月份是从0开始的
        let day = String(dateObj.getDate()).padStart(2, '0');

        // 设置默认时间为18:59:21，您可以根据需求修改这里的时间
        let defaultTime = "00:00:00";
        let [hours, minutes, seconds] = defaultTime.split(':');

        // 构建最终的日期时间字符串
        return `${year}-${month}-${day} ${hours.padStart(2, '0')}:${minutes.padStart(2, '0')}:${seconds.padStart(2, '0')}`;
    }

}

export async function urlToFileWithFormData(url, fileName) {
    try {
        // 1. 获取图片数据
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        // 2. 获取 blob 数据
        const blob = await response.blob();

        // 3. 创建 File 对象
        const file = new File([blob], fileName, { type: blob.type });

        // 4. 创建 FormData 并添加文件
        const formData = new FormData();
        formData.append('file', file);

        return formData;
    } catch (error) {
        console.error('图片转换失败:', error);
        throw error;
    }
}

export function printFormData(formData) {
    const result = {};
    for (const [key, value] of formData.entries()) {
        if (result[key]) {
            // 处理重复键（如多文件上传）
            result[key] = Array.isArray(result[key])
                ? [...result[key], value]
                : [result[key], value];
        } else {
            result[key] = value;
        }
    }
    console.log(result);
    return result;
}